package com.qiyang.login.controller;

import com.qiyang.api.log.LogApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

/**
 * Created on 2018/4/29.
 *
 * @author sehuaqi.
 * 描述：请求控制层 C
 */
@Controller
@RequestMapping("/login")
public class LoginViewController {

    Logger log = LoggerFactory.getLogger(LoginViewController.class);

    @Autowired
    private LogApi logApi;

//    @Autowired
//    private AuthrizationApi authrizationApi;

    @Value("${service.version}")
    private String version;

    @Autowired
    private RestTemplate template;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * @param modelMap
     * @return
     **/
    @GetMapping("")
    /*@HystrixCommand(fallbackMethod = "loginError")*/
    public String login(ModelMap modelMap, HttpServletRequest request) {

        String logStatus = logApi.printLog("Feign调用，进入登录页面" + request.getRemoteAddr());

        /*ModelAndView modelAndView = new ModelAndView();

        String logStatus = logApi.printLog("Feign调用，进入登录页面" + request.getRemoteAddr());

        ServiceInstance serviceInstance = loadBalancerClient.choose("service-log-v1");

        String customParam = serviceInstance.getMetadata().get("custom-param");

        String serverVersion = serviceInstance.getMetadata().get("server-v");

        log.info("customParam:{},serverVersion:{}", customParam, serverVersion);*/


        modelMap.put("defaultUserName", "admin");

        //String loginInfo = "进入登录页面" + request.getRemoteAddr();

        //String logStatus = template.getForEntity("http://service-log-v1/log/printLog?info=" + loginInfo, String.class).getBody();

        modelMap.put("log_status", logStatus);

        modelMap.put("version", version);

        log.info("<您访问的是：{}>", version);

        return "login";
    }

    /**
     * 服务降级处理，已使用Feign服务降级方式替代
     * @param modelMap
     * @param request
     * @return
     */
    public String loginError(ModelMap modelMap, HttpServletRequest request) {

        log.info("调用日志服务失败，进入熔断器");

        modelMap.put("log_status", "error");

        modelMap.put("version", "error");

        modelMap.put("defaultUserName", "admin");

        return "login";
    }

}
